<template>
  <div class="p-6px">
    <el-card class="rounded-md" shadow="never">
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true" id="searchFormId" @submit.native.prevent>
        <el-form-item label="分类名称" prop="name">
          <el-input
            placeholder="请输入分类名称"
            v-model="searchParams.name"
            clearable
            style="width: 200px"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain v-debounce="handleSearch">搜索</el-button>
          <el-button type="danger" icon="refresh" plain v-throttle="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['system:role:add']">
          <el-button type="primary" icon="plus" plain @click="handleAdd()">新增</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleListPage"></KoiToolbar>
      </el-row>

      <br/>
      <!-- 数据表格 :data="tableList" -->
      <el-table v-loading="loading" v-adaptive border :data="tableList" empty-text="暂时没有数据哟">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="序号" prop="id" width="80px" align="center" type="index"></el-table-column>
        <el-table-column
          label="分类名称"
          prop="name"
          width="120px"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="是否超级商户" prop="is_super_category" width="120px" align="center"
                         :show-overflow-tooltip="true">
          <template #default="scope">
            {{ scope.row.is_super_category ? "超级商户" : "普通商户" }}
          </template>
        </el-table-column>
        <el-table-column label="默认开通时效" prop="open_time" width="150px" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            {{ scope.row.open_time }}
            {{
              (koiDicts.sys_merchant_category_open_type || []).find((r: any) => r.dictValue === scope.row.open_type)?.dictLabel
            }}
          </template>
        </el-table-column>

        <!-- 注意：如果后端数据返回的是字符串"0" OR "1",这里的active-value AND inactive-value不需要加冒号，会认为是字符串，否则：后端返回是0 AND 1数字，则需要添加冒号 -->
        <el-table-column label="状态" prop="status" width="100px" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-text="启用"
              inactive-text="禁用"
              :active-value="0"
              :inactive-value="1"
              :inline-prompt="true"
              @change="handleSwitch(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="created_at" width="180px" align="center"></el-table-column>
        <el-table-column label="备注" prop="remark" width="200px" align="center"
                         :show-overflow-tooltip="true"></el-table-column>
        <el-table-column
          label="操作"
          align="left"
          width="350"
          fixed="right"
          v-auth="['system:role:update', 'system:role:delete']"
        >
          <template #default="{ row }">
            <el-button type="primary" size="small" plain @click="handleUpdate(row)" v-auth="['system:role:update']">
              修改
            </el-button>
            <el-button type="primary" size="small" plain @click="handleAssignMenu(row)" v-auth="['system:user:role']">
              分配菜单
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <br/>
      <!-- 分页 -->
      <el-pagination
        background
        v-model:current-page="searchParams.pageNo"
        v-model:page-size="searchParams.pageSize"
        v-show="total > 0"
        :page-sizes="[10, 20, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleListPage"
        @current-change="handleListPage"
      />

      <!-- 添加 OR 修改 -->
      <KoiDrawer
        ref="koiDrawerRef"
        :title="title"
        @koiConfirm="handleConfirm"
        @koiCancel="handleCancel"
        :loading="confirmLoading"
      >
        <template #content>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="80px" status-icon>
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="分类名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入分类名称" clearable/>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="类型" prop="is_super_category">
                  <el-select v-model="form.is_super_category" placeholder="请选择超级商户" clearable>
                    <el-option label="普通商户" :value="0"/>
                    <el-option label="超级商户" :value="1"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="开通时效" prop="open_time">
                  <el-input-number v-model="form.open_time" placeholder="请输入开通时效"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="开通类型" prop="open_type">
                  <el-select v-model="form.open_type" placeholder="请选择超级商户" clearable>
                    <el-option
                      v-for="item in koiDicts.sys_merchant_category_open_type"
                      :key="item.dictValue"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" :rows="5" type="textarea" placeholder="请输入备注"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </KoiDrawer>

      <!-- 分配菜单 -->
      <KoiDrawer
        ref="allocationMenuDrawerRef"
        title="分配菜单"
        size="360"
        @koiConfirm="handleMenuConfirm"
        @koiCancel="handleMenuCancel"
        :loading="confirmLoading"
        cancelText="关闭"
      >
        <template #content>
          <div>
            <el-tree
              ref="treeRef"
              :data="treeData"
              show-checkbox
              :default-expand-all="false"
              :default-expanded-keys="expandedKey"
              node-key="menuId"
              highlight-current
              :props="defaultProps"
            />
          </div>
        </template>
      </KoiDrawer>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="merchantCategoryPage">
// 已使用字典案例
import {onMounted, reactive, ref} from "vue";
// @ts-ignore
import {koiMsgBox, koiMsgError, koiMsgSuccess, koiMsgWarning, koiNoticeError, koiNoticeSuccess} from "@/utils/koi.ts";
// @ts-ignore
import {
  add,
  getById,
  listMenuIdsByCategoryId,
  listPage,
  saveCategoryMenu,
  update,
  updateStatus
} from "@/api/merchant/category/index.ts";
import {listMenuNormal} from "@/api/merchant/menu/index.ts";
// @ts-ignore
import {handleTree, koiDatePicker} from "@/utils/index.ts";
import {useKoiDict} from "@/hooks/dicts/index.ts";

// 数据表格加载页面动画
const loading = ref(false);
/** 是否显示搜索表单 */
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 数据表格数据
const tableList = ref<any>([]);
const {koiDicts} = useKoiDict(["sys_merchant_category_open_type"]);

// 查询参数
const searchParams = ref({
  pageNo: 1, // 第几页
  pageSize: 10, // 每页显示多少条
  name: ""
});

const total = ref<number>(0);

// 重置搜索参数
const resetSearchParams = () => {
  searchParams.value = {
    pageNo: 1,
    pageSize: 10,
    name: ""
  };
};

/** 搜索 */
const handleSearch = () => {
  console.log("搜索");
  searchParams.value.pageNo = 1;
  handleListPage();
};

/** 重置 */
const resetSearch = () => {
  console.log("重置搜索");
  resetSearchParams();
  handleListPage();
};

/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选中条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const handleListPage = async () => {
  try {
    loading.value = true;
    tableList.value = []; // 重置表格数据
    const res: any = await listPage(searchParams.value);
    console.log("用户数据表格数据->", res.data);
    tableList.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试");
  }
};

/** 数据表格[删除、批量删除等刷新使用] */
const handleTableData = async () => {
  try {
    const res: any = await listPage(koiDatePicker(searchParams.value, dateRange.value));
    // console.log("用户数据表格数据->", res.data);
    tableList.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试");
  }
};

onMounted(() => {
  // 获取数据表格数据
  handleListPage();
});

/** 添加 */
const handleAdd = () => {
  // 重置表单
  resetForm();
  // 标题
  title.value = "添加";
  form.value.status = "0";
  koiDrawerRef.value.koiOpen();
  koiMsgSuccess("添加");
};

/** 回显数据 */
const handleEcho = async (id: any) => {
  console.log("回显数据ID", id);
  if (id == null || id == "") {
    koiMsgWarning("请选择需要修改的数据");
    return;
  }
  try {
    const res: any = await getById(id);
    console.log(res.data);
    form.value = res.data;
  } catch (error) {
    koiNoticeError("数据获取失败，请刷新重试");
    console.log(error);
  }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 重置表单
  resetForm();
  // 标题
  title.value = "修改";
  const id = row.id;
  if (id == null || id == "") {
    koiMsgError("请选中需要修改的数据");
  }
  // 回显数据
  handleEcho(id);
  koiDrawerRef.value.koiOpen();
};

/** 添加 AND 修改抽屉 */
const koiDrawerRef = ref();
// 标题
const title = ref("类型管理");
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  name: "",
  is_super_category: 0,
  open_time: "1",
  open_type: "year",
  remark: ""
});

/** 清空表单数据 */
const resetForm = () => {
  form.value = {
    name: "",
    is_super_category: 0,
    open_time: "1",
    open_type: "year",
    remark: ""
  };
};

/** 表单规则 */
const rules = reactive({
  username: [{required: true, message: "请输入用户名字", trigger: "blur"}],
  nickname: [{required: true, message: "请输入用户类型", trigger: "blur"}],
  status: [{required: true, message: "请输入选择用户状态", trigger: "blur"}]
});

// 确定按钮是否显示loading
const confirmLoading = ref(false);
/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      console.log("表单ID", form.value.id);
      if (form.value.id != null && form.value.id != "") {
        try {
          await update(form.value);
          koiNoticeSuccess("修改成功");
          confirmLoading.value = false;
          koiDrawerRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiNoticeError("修改失败，请刷新重试");
        }
      } else {
        try {
          await add(form.value);
          koiNoticeSuccess("添加成功");
          confirmLoading.value = false;
          koiDrawerRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiNoticeError("添加失败，请刷新重试");
        } finally {
          confirmLoading.value = false;
        }
      }
    } else {
      koiMsgError("验证失败，请检查填写内容");
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDrawerRef.value.koiClose();
};

/** 状态switch */
const handleSwitch = (row: any) => {
  let text = row.status == "0" ? "启用" : "停用";
  koiMsgBox("确认要[" + text + "]-[" + row.nickname + "]吗？")
    .then(async () => {
      resetForm();
      if (!row.id) {
        koiMsgWarning("请选择需要修改的数据");
        return;
      }
      try {
        await updateStatus(row.id, row.status);
        koiNoticeSuccess("修改成功");
      } catch (error) {
        console.log(error);
        koiNoticeError("修改失败，请刷新重试");
        handleTableData();
      }
    })
    .catch(() => {
      koiMsgError("已取消");
    });
};

const allocationMenuDrawerRef = ref();
const treeRef = ref();
const treeData = ref<any>([]);

// 配置属性
const defaultProps = {
  id: "menuId",
  label: "menuName",
  children: "children"
};
// 默认展开配置
const expandedKey = ref();
const categoryId = ref();
/** 分配菜单 */
const handleAssignMenu = async (row?: any) => {
  // 置空
  treeRef.value?.setCheckedKeys([], false);
  categoryId.value = row?.id;
  if (categoryId.value == null || categoryId.value == "") {
    koiMsgWarning("请选中需要分配菜单的数据");
    return;
  }
  // 查询所有的菜单权限
  allocationMenuDrawerRef.value.koiOpen();
  // console.log("角色ID",ids.value[0]);
  // 查询所有的菜单权限
  try {
    const res: any = await listMenuNormal();
    treeData.value = handleTree(res.data.menuList, "menuId");
    expandedKey.value = res.data.spreadList;
  } catch (error) {
    console.log(error);
    koiMsgError("菜单资源加载失败");
  }

  // 通过key设置反选角色拥有的菜单权限(只能查询子节点，查询父节点将直接选中全部下的子节点)
  try {
    const res: any = await listMenuIdsByCategoryId(categoryId.value);
    // console.log('res',res.data)
    // reeRef.value?.setCheckedKeys([1,2,3], false);
    if (res.data) {
      treeRef.value?.setCheckedKeys(res.data, false);
    }
  } catch (error) {
    console.log(error);
    koiMsgError("角色菜单资源加载失败");
  }
};

// 保存
const handleMenuConfirm = async () => {
  confirmLoading.value = true;
  // 获取选中的keys
  const checkedKeys = treeRef.value?.getCheckedKeys(false);
  // console.log("选中",checkedKeys)
  // 获取半选的keys(即保存选中子节点的父节点[父节点下的子节点并没有选中完])
  const halfCheckKeys = treeRef.value?.getHalfCheckedKeys();
  // console.log("半选",halfCheckKeys)
  // 组合成最后的keys
  const finalKey = halfCheckKeys.concat(checkedKeys);
  // console.log("最终",finalKey)

  try {
    await saveCategoryMenu(categoryId.value, finalKey);
    confirmLoading.value = false;
    koiNoticeSuccess("角色菜单保存成功");
    // 刷新页面菜单信息
    window.location.reload;
  } catch (error) {
    console.log(error);
    koiMsgError("角色菜单保存失败");
  } finally {
    confirmLoading.value = false;
  }
};

// 取消
const handleMenuCancel = () => {
  allocationMenuDrawerRef.value.koiClose();
};
</script>

<style lang="scss" scoped>
// 穿梭框高度调整
:deep(.el-transfer-panel__body) {
  height: 400px;
}
</style>
